package com.cwh.taskcenter.task.gateway;

import com.cwh.taskcenter.domain.task.gateway.UserTaskGateWay;
import com.cwh.taskcenter.domain.task.model.UserTask;
import com.cwh.taskcenter.task.converter.UserTaskConverter;
import com.cwh.taskcenter.task.mapper.UserTaskMapper;
import com.cwh.taskcenter.task.model.UserTaskDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author cwh
 */
@Component
public class UserTaskGateWayImpl implements UserTaskGateWay {

    @Autowired
    private UserTaskMapper userTaskMapper;

    @Override
    public void save(UserTask userTask) {
        UserTaskDO userTaskDO = UserTaskConverter.toUserTaskDO(userTask);
        userTaskMapper.create(userTaskDO);
    }

    @Override
    public void update(UserTask userTask) {
        UserTaskDO userTaskDO = UserTaskConverter.toUserTaskDO(userTask);
        userTaskMapper.update(userTaskDO);
    }

    @Override
    public Long saveOrUpdate(UserTask userTask) {
        UserTaskDO userTaskDO = UserTaskConverter.toUserTaskDO(userTask);
        if (userTask.getId() == null) {
            userTaskMapper.create(userTaskDO);
        }else {
            userTaskMapper.update(userTaskDO);
        }
        return userTaskDO.getUserId();
    }


    @Override
    public boolean isUserTaskAccepted(Long taskId, Long userId) {
        UserTaskDO userTaskDO = userTaskMapper.findByTaskIdAndUserId(taskId, userId);
        return userTaskDO != null;
    }

    @Override
    public void batchUpdate(List<UserTask> userTaskList) {
        userTaskList.forEach(userTask -> {
            userTaskMapper.update(UserTaskConverter.toUserTaskDO(userTask));
        });
    }

    @Override
    public int countByTaskIdAndUserId(Long taskId, Long userId) {
        return userTaskMapper.countByTaskIdAndUserId(taskId, userId);
    }
}
